package com.myway.utils.eamil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Date;
import java.util.Properties;

/**
 * Created by whuang on 2018/10/23.
 */
public class EmailUtils {

    /**
     * @param toEmail
     * @param subjectStr
     * @param contextStr
     * @desc 发送邮件验证码
     */
    public static void sendHtmlEmail(String toEmail, String subjectStr, String contextStr, String filesPath) {

        System.out.println("====================================send email start(" + new Date() + ")======================================");
        try {
            Properties fileprops = PropertiesLoaderUtils.loadProperties(new ClassPathResource("emailconfig.properties"));
            String stmpHost = fileprops.getProperty("email_smtphost");
            String smtpport = fileprops.getProperty("email_smtpport");
            String fromemail = fileprops.getProperty("email_fromemail");
            String username = fileprops.getProperty("email_username");
            String password = fileprops.getProperty("email_password");
            String emailtype = fileprops.getProperty("email_type");
            String email_cc = fileprops.getProperty("email_cc");

            Properties props = new Properties();

            // 设置发送邮件的邮件服务器的属性（这里使用网易的smtp服务器）
            props.put("smtp.mxhichina.com", stmpHost);
            // 需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）
            props.put("mail.smtp.auth", "true");

            // 用刚刚设置好的props对象构建一个session
            Session session = Session.getDefaultInstance(props);
            // 用（你可以在控制台（console)上看到发送邮件的过程）
            session.setDebug(true);
            // 用session为参数定义消息对象
            MimeMessage message = new MimeMessage(session);
            try {
                // 加载发件人地址
                message.setFrom(new InternetAddress(fromemail));
                // 加载收件人地址
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
                // 加载标题
                message.setSubject(subjectStr);
                // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
                Multipart multipart = new MimeMultipart();
                // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
                // 创建一个包含HTML内容的MimeBodyPart
                BodyPart html = new MimeBodyPart();
                // 设置HTML内容
                html.setContent(contextStr, "text/html; charset=utf-8");
                multipart.addBodyPart(html);

                if (!StringUtils.isEmpty(filesPath)) {
                    for (String fileStr : filesPath.split(",")) {
                        // 附件部分
                        File tempFile = new File(fileStr.trim());
                        String fileName = tempFile.getName();
                        MimeBodyPart messageBodyPart = new MimeBodyPart();
                        DataSource source = new FileDataSource(fileStr);
                        messageBodyPart.setDataHandler(new DataHandler(source));
                        messageBodyPart.setFileName(fileName);
                        multipart.addBodyPart(messageBodyPart);
                    }
                }

                // 将multipart对象放到message中
                message.setContent(multipart);
                // 设置邮件消息发送的时间
                message.setSentDate(new Date());
                //抄送人员 任东辉
                if (!StringUtils.isEmpty(email_cc)) {
                    String[] emailCcArr = email_cc.split(",");
                    for (String str : emailCcArr) {
                        message.addRecipient(Message.RecipientType.CC, new InternetAddress(str));
                    }
                }
                // 保存邮件
                message.saveChanges();
                // 发送邮件
                Transport transport = getEmailSession(stmpHost, smtpport, username, password).getTransport(emailtype);
                // 连接服务器的邮箱
                transport.connect(stmpHost, username, password);
                // 把邮件发送出去
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("====================================send email end(" + new Date() + ")======================================");

        } catch (Exception ee) {
            ee.printStackTrace();
        }

    }

    /**
     * @return
     * @desc 创建一个邮件会话session
     */
    public static Session getEmailSession(String stmpHost, String smtpPort, String userName, String password) {
        Properties mailProperties = new Properties();
        mailProperties.setProperty("mail.smtp.host", stmpHost);
        mailProperties.setProperty("mail.smtp.port", smtpPort);
        mailProperties.setProperty("mail.smtp.auth", "true");
        mailProperties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        MyAuthenticator authenticator = new MyAuthenticator(userName, password);
        return Session.getInstance(mailProperties, authenticator);
    }

}
